# add update time to meta
import os
import re
import time


def insert_title(md_file):
    path_pre = '/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/docs/'
    pattern = re.compile(r': (.*?).md', re.S)
    filepath_list = []  # md files 
    with open(md_file) as md:
        for line in md.readlines():
            line = str(line)
            cur_urls = re.findall(pattern, line)
            if len(cur_urls) > 0:
                if cur_urls[0] == '/':
                    continue
                filepath_list.append(path_pre + cur_urls[0] + '.md')

    print('md files count: ', len(filepath_list))

    err_filepath_list = []
    for md_file in filepath_list:
        if not os.path.exists(md_file):
            err_filepath_list.append(md_file)
            continue
        has_updated_time = False
        has_title_meta = False
        with open(md_file) as md:
            for line in md.readlines():
                line = str(line)
                if line.startswith("title: "):
                    has_title_meta = True
                    continue
                if line.startswith("updated_time: 20"):
                    has_updated_time = True
                    continue
        if not has_updated_time and has_title_meta:
            print('meta has title but no update time', md_file)
            meta_add_update_time(md_file)


def meta_add_update_time(md_file):
    time1 = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime()) 
    tmp_content = []
    with open(md_file, "r") as f:
        tmp_content = f.readlines()
    tmp_content.insert(2, 'updated_time: ' + time1 + '+08:00\n')
    with open(md_file, "w") as f:
        f.writelines(tmp_content)


if __name__ == '__main__':
    print('go ----- ')
    insert_title('/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/mkdocs.yml')
